package com.example.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/sentinel")
public class SentinelFlowControlController {

    private static final Logger logger = LoggerFactory.getLogger(SentinelFlowControlController.class);

    @GetMapping("/flow-control")
    @SentinelResource(value = "flowControlResource", blockHandler = "handleFlowControlException")
    public String handleFlowControl() {
        logger.info("处理 /flow-control 请求");
        return "请求成功，流控策略正常工作";
    }

    public String handleFlowControlException(BlockException ex) {
        logger.warn("请求被限流或降级：{}", ex.getMessage());
        return "请求被限流或降级，请稍后再试";
    }

    @GetMapping("/circuit-breaker")
    @SentinelResource(value = "circuitBreakerResource", blockHandler = "handleCircuitBreakerException")
    public String handleCircuitBreaker() {
        logger.info("处理 /circuit-breaker 请求");
        // 模拟业务异常
        if (Math.random() > 0.5) {
            throw new RuntimeException("模拟业务异常");
        }
        return "请求成功，熔断策略正常工作";
    }

    public String handleCircuitBreakerException(BlockException ex) {
        logger.warn("请求被熔断或降级：{}", ex.getMessage());
        return "请求被熔断或降级，请稍后再试";
    }

    @GetMapping("/hot-spot")
    @SentinelResource(value = "hotSpotResource", blockHandler = "handleHotSpotException")
    public String handleHotSpot() {
        logger.info("处理 /hot-spot 请求");
        return "请求成功，热点参数策略正常工作";
    }

    public String handleHotSpotException(BlockException ex) {
        logger.warn("请求被热点限流或降级：{}", ex.getMessage());
        return "请求被热点限流或降级，请稍后再试";
    }

    @GetMapping("/system")
    @SentinelResource(value = "systemRuleResource", blockHandler = "handleSystemRuleException")
    public String handleSystemRule() {
        logger.info("处理 /system 请求");
        return "请求成功，系统规则策略正常工作";
    }

    public String handleSystemRuleException(BlockException ex) {
        logger.warn("请求被系统规则限流或降级：{}", ex.getMessage());
        return "请求被系统规则限流或降级，请稍后再试";
    }

    @GetMapping("/authority")
    @SentinelResource(value = "authorityRuleResource", blockHandler = "handleAuthorityRuleException")
    public String handleAuthorityRule() {
        logger.info("处理 /authority 请求");
        return "请求成功，授权规则策略正常工作";
    }

    public String handleAuthorityRuleException(BlockException ex) {
        logger.warn("请求被授权规则限制：{}", ex.getMessage());
        return "请求被授权规则限制，请稍后再试";
    }
}
